package com.linking.web.pojo.bo;

import com.google.common.collect.Lists;
import java.util.List;
import lombok.Data;
import org.apache.commons.lang3.ObjectUtils;

/**
 * 分页对象
 *
 * @author yaoweixin
 * @date 2019/03/07
 */
@Data
public class PageBO {

  private Long count;
  private Long page;
  private Long pageSize;
  private Long maxPage;

  public static PageBO of(Long count, Long page, Long pageSize) {
    long size = 10;
    page = ObjectUtils.allNotNull(page) ? page : 1;
    pageSize = ObjectUtils.allNotNull(pageSize) ? pageSize : size;
    long mvMaxPageSize = 5000;
    if (pageSize <= 0) {
      pageSize = size;
    }
    if (pageSize > mvMaxPageSize) {
      pageSize = mvMaxPageSize;
    }
    long maxPage = count / pageSize;
    if (count % pageSize > 0) {
      maxPage += 1;
    }
    if (maxPage <= 0) {
      maxPage = 1;
    }
    if (page < 0) {
      page = 1L;
    }

    PageBO vo = new PageBO();
    vo.setCount(count);
    vo.setPage(page);
    vo.setPageSize(pageSize);
    vo.setMaxPage(maxPage);
    return vo;
  }

  public <T> List<T> pagination(List<T> list) {
    List<T> sortList = Lists.newArrayList();
    int start = (int)((this.getPage() - 1) * this.getPageSize());
    int size = (int)(this.getPage() * this.getPageSize());
    for (; start < size; start ++) {
      if (start >= list.size()) {
        break;
      }
      sortList.add(list.get(start));
    }
    return sortList;
  }
}